import {createContext, Reducer, useReducer} from 'react'

interface State {
  counter: number
}

interface Injected extends State {
  increment: () => any,
  decrement: () => any
}

interface Props {
  children?: any
}

type Action = {
  type: string,
  [key: string]: any
}

const initialState = { counter: 0 }

export const context = createContext<Injected>(initialState as Injected)

const reducer: Reducer<State, Action> = (state, action) => {
  if (action.type == 'increment') {
    return {
      counter: state.counter + 1
    }
  }

  if (action.type == 'decrement') {
    return {
      counter: state.counter - 1
    }
  }
  return state
}

export function Provider({children}: Props) {
  const [state, dispatch] = useReducer(reducer, initialState)

  const value = {
    counter: state.counter,
    increment: () => dispatch({ type: 'increment' }),
    decrement: () => dispatch({ type: 'decrement' }),
  }

  return (
    <context.Provider value={value}>
      {children}
    </context.Provider>
  )
}